//////////////
// INCLUDES //
//////////////
#include "lib.h"

#include "bjgame.h"
#include "bjbet.h"
#include "bjconn.h"
#include "bjshoe.h"
#include "bjhand.h"
#include "cardmgr.h"
#include "bjsaved.h"
#include "bjrules.h"
#include "stdncerr.h"
#include <ctype.h>


bool8
BJBet::HandlePlayerInsurance(int32 sidebet)
{
	int32 balance;

    //must be a dealer hand
	if (!dealer )
		return false;

	if( m_insuranceState != OFFERED )
		return false;

    // if sidebet=0 --> player declined insurance
    // No Insurance button was pressed
    if( sidebet == 0 )
    {
    	m_insuranceState = DECLINED;	
		conn->trackGetBalance(&balance);
    }
    else
    {
    	m_insuranceState = TAKEN;
	    // Only track bet -- we will track payout later
	    conn->trackInsuranceState(gid, m_insuranceState, 0, &balance);	//taken
    }

    // kharmon.  06-28-06.  Do NOT trust the "sidebet" value that the client sent us!
    // Instead calculate the cost of the sidebet using what we know to be the correct cost of the bet.
    m_insurance = (int32) (this->m_bet * this->m_pRules->getInsuranceCostPercentage());

	//if not saving fun play data, deduct the insurance bet when it is made
	if(! conn->shouldSaveGameData())
	{
		if(m_insuranceState == TAKEN)
			balance = conn->trackAdjustBalance(-m_insurance);
	}

	//acknowledge the initial sidebet
	conn->msgStart();
	conn->SENDBYTE('I');
	conn->SENDBYTE(m_insuranceState);	

	//amount
	conn->SENDINT4(sidebet);

	//balance
	conn->SENDINT4(balance);
	conn->SENDBYTE(m_iBJBet);

	conn->msgEnd();

	return true;
}

void
BJBet::HandlePlayerInsurancePayout()
{
	int32 payout;
	int32 balance;

	//can the insurance bet resolve
	int canresolve = m_pRules->CanPayout( m_insurance, dealer );
	if (!canresolve)
		return;

	payout = m_pRules->GetPayout( Insure, m_insurance, current, dealer );

	//INSURANCE LOSES
	if (payout==0)
	{
		// all insurance bets lose...game continues
		payout = -m_insurance;

		// On a loss, we have already tracked the money out of the account - just get the balance
		conn->trackGetBalance(&balance);

		m_insuranceState = LOST;	//LOST
	}
	else if (payout > 0)
	{
		// Only set payout -- bet has already been registered
		conn->trackInsuranceState(gid, 0, payout, &balance);	//won
		dealer->RevealAllCards();
		m_insuranceState = WON;	//WON

		//when not saving fun play data update the account with the insurance win
		if(! conn->shouldSaveGameData())
			balance = conn->trackAdjustBalance(payout);
	}
	else
	{
		//PAYOUT < 0
		//THIS SHOULD NOT HAPPEN
		conn->Error(LOGINERR_CONTACTCUSTSERVICE); 
        return;
	}

    conn->trackSaveGame();

	conn->msgStart();
	conn->SENDBYTE('I');
    conn->SENDBYTE(m_insuranceState);
	conn->SENDINT4( payout );
	conn->SENDINT4(balance);
	conn->SENDBYTE(m_iBJBet);
    if( m_insuranceState == WON )
		dealer->send(conn);         //send the dealer's hand 


	conn->msgEnd();
}


